# ###########################
from chiori import Plugin
from libs.vk import get_ids, get_profiles, get_id
import time
# ###########################

p = Plugin('vk: mesanger', backend='vk_cli', sp=['vk'])

def print_message(profiles, m, reply=0, print_name= True):
	date = time.ctime(m['date'])
	profile = profiles[str(m['from_id'])]

	message_id = m['conversation_message_id']

	text = f'{"  |--"*reply}\033[93m#{message_id} \033[33m{date}'

	if m.get('reply_message'):
		text += f' \033[0m(-> \033[93m#{m["reply_message"]["conversation_message_id"]}\033[0m)'

	if print_name:
		text += f' \033[94m{profile["first_name"]}'

	text += f' \033[0m{m["text"]}'

	print(text)

	for x in m.get("fwd_messages", []):
		print_message(profiles, x, reply= (reply + 1))

	for a in m['attachments']:
		print(f'  {"  |--"*reply}[{a["type"]}]: {a}')


@p.command('chat')
async def getChat(event, ctx):
	targets = await get_ids(event, ctx)

	for x in targets:
		res = await ctx.request('messages.getHistory', peer_id=x, count=25)
		profiles = await get_profiles(event, ctx, [event.get('from.id'), x])

		if res['error']:
			continue

		l_id = ''
		l_day = ''

		for m in res['response']['items'][::-1]:
			if m['from_id'] != l_id:
				print_name = True
				l_id = m["from_id"]
			else:
				print_name = False

			print_message(profiles, m, print_name=print_name)


@p.command('message')
async def sendMessage(event, ctx):
	target, args = await get_id(event, ctx)

	if target:
		await ctx.request('messages.send', peer_id=target, message=args, random_id="0")
